package ar.com.ford.it.fullEconomics.view.action;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.AgreementFacade;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.facade.VehiclelinFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.AgreementFindStruct;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.util.XlsPrinter;
import ar.com.ford.it.fullEconomics.view.form.AgreementsForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class AgreementsAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param Agreement
     * Agreement donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    private Collection getDateFieldsCombo(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        list.add(new OptionCombo("I", resources
                .getMessage("agreement.label.issue")));
        list.add(new OptionCombo("S", resources
                .getMessage("agreement.label.signature")));
        list.add(new OptionCombo("R", resources
                .getMessage("agreement.label.tableHeader.register")));
        list.add(new OptionCombo("E", resources
                .getMessage("agreement.lable.effective")));

        return list;
    }

    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementsForm AgreementForm = (AgreementsForm) actionForm;
        AgreementForm.resetForm();
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        VehiclelinFacade lineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);
        request.getSession().setAttribute("dateFields",
                this.getDateFieldsCombo(request));
        request.getSession().setAttribute("partClassColl",
                commodityFacade.getPartClases());
        try {
            request.getSession().setAttribute(
                    "commColl",
                    commodityFacade.findCommodities("", "", user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("lineColl",
                    lineFacade.findAllVehiclelin());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward cleanCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        AgreementsForm AgreementForm = (AgreementsForm) actionForm;
        AgreementForm.cleanCreateFields();
        return mapping.findForward("success");
    }

    public ActionForward createAgreement(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementsForm form = (AgreementsForm) actionForm;
        AgreementFacade AgreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        String forward = "success";

        try {
            if (form.getEditBlocked().equalsIgnoreCase("false")) {
                Teess01Supplier supplier = new Teess01Supplier();
                supplier.setEess01SupplierClassCodeC(form.getSupplierClass());
                supplier.setEess01SupplierCodeC(form.getSupplierCode());
                supplier.setEess01PlantCodeC(user.getTeesg01Plant());
                supplier = supplierFacade.getSupplierByPk(supplier);
                if (supplier != null) {
                    Teesr03Agreement agreement = form.getAgreementForCreate();
                    agreement.setTeess01Supplier(supplier);
                    agreement = AgreementFacade
                            .createAgreement(agreement, user);
                    request.setAttribute("AgreementSelected", agreement);
                } else {
                    am
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "customMessage",
                                            resources
                                                    .getMessage("agreement.error.invalidSupplier")));
                    saveErrors(request, am);
                    forward = "error";
                }
            }
            if (form.getEditBlocked().equalsIgnoreCase("true")) {
                Teesr03Agreement req = form.getAgreementForUpdate();
                AgreementFacade.updateAgreement(req, user);
                request.setAttribute("AgreementSelected", req);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward(forward);
    }

    public ActionForward deleteAgreement(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementsForm form = (AgreementsForm) actionForm;
        AgreementFacade AgreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);

        try {
            AgreementFacade.deleteAgreement(form.getAgreementSelected(form
                    .getSelectedIndex()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward findAgreements(FordActionMapping mapping,
                                        ActionForm actionForm,
                                        HttpServletRequest request,
                                        HttpServletResponse response,
                                        WebSession webSession,
                                        ActionMessages msgs,
                                        ActionMessages warns,
                                        ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementsForm form = (AgreementsForm) actionForm;
        AgreementFacade AgreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);

        VehiclelinFacade lineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);

        try {
        	Ncas012VehicleVw vehicleLine = new Ncas012VehicleVw();
            vehicleLine.setCas012VehicleCodeC(form.getVehicleLine());
            AgreementFindStruct findStruct = new AgreementFindStruct();
            findStruct.setSupplierClass(form.getSupplierClassFind());
            findStruct.setSupplierCode(form.getSupplierCodeFind());
            findStruct.setSupplierName(form.getSupplierNameFind());
            findStruct.setCommodity(new Integer(form.getCommodityCode()));
            findStruct.setPartClass(form.getPartClass());
            findStruct.setPrefix(form.getPrefix());
            findStruct.setBase(form.getBase());
            findStruct.setSuffix(form.getSuffix());
            findStruct.setDateField(form.getDateFilter());
            findStruct.setUserCode(form.getUserCode());
            findStruct.setVehicleLine(lineFacade
                    .findVehicleLineByPk(vehicleLine));
            if (!form.getDateFilter().equals("-1")) {
                findStruct.setDateFrom(new Timestamp(FullEconomicsDateUtil
                        .format(form.getDateFrom()).getTimeInMillis()));
                findStruct.setDateTo(new Timestamp(FullEconomicsDateUtil
                        .format(form.getDateTo()).getTimeInMillis()));
            }
            findStruct.setPlant(user.getTeesg01Plant());
            form.setAgreementColl(AgreementFacade.findAgreements(findStruct));
            if (form.getAgreementColl().isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward editItems(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        AgreementsForm form = (AgreementsForm) actionForm;
        request.setAttribute("agreementSelected", form.getAgreementSelected());

        return mapping.findForward("success");
    }

    public ActionForward editAgreement(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {

        AgreementsForm form = (AgreementsForm) actionForm;

        form.setAgreementForEdit(form.getAgreementSelected(form
                .getSelectedIndex()));

        return mapping.findForward("success");
    }

    public ActionForward viewObs(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        AgreementsForm form = (AgreementsForm) actionForm;
        String selectedIndex = request.getParameter("selectedIndex");
        request.setAttribute("agreementSelected", form
                .getAgreementSelected(selectedIndex));

        return mapping.findForward("success");
    }

    /**
     * Genera un reporte en excel de los agreements seleccionados en el filtro
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward reportAgreements(FordActionMapping mapping,
                                          ActionForm actionForm,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          WebSession webSession,
                                          ActionMessages msgs,
                                          ActionMessages warns,
                                          ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementsForm form = (AgreementsForm) actionForm;
        XlsPrinter xlsPrinter = new XlsPrinter();

        OutputStream out = null;
        String forward = "success";
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            xlsPrinter.reportAgreement(workbook, form.getAgreementSelected(), request);
            
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=sampleName.xls");
            out = response.getOutputStream();
            workbook.write(out); 
            if(out != null)
                out.close();
        }catch (FullEconomicsException e) {
            if(e.getArgument() == null){
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            }else{
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource(),e.getArgument()));
            }
            saveErrors(request, am);
            forward="error";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return mapping.findForward(forward);
    }
}
